import { Router } from 'express';
import { body } from 'express-validator';
import validateFormData from '../helpers/validate_form.js';
import DB from '../models/db.js';


const router = Router();




/**
 * Route to list blocks records
 * @GET /blocks/index/{fieldname}/{fieldvalue}
 */
router.get(['/', '/index/:fieldname?/:fieldvalue?'], async (req, res) => {
	try {
		const query = {};
		let queryFilters = [];
		let where = {};
		let replacements = {};
		let fieldName = req.params.fieldname;
		let fieldValue = req.params.fieldvalue;

		if (fieldName) {
			queryFilters.push(DB.filterBy(fieldName, fieldValue));
		}
		let search = req.query.search;
		if (search) {
			let searchFields = DB.Blocks.searchFields();
			where[DB.op.or] = searchFields;
			replacements.search = `%${search}%`;
		}

		if (queryFilters.length) {
			where[DB.op.and] = queryFilters;
		}
		query.raw = true;
		query.where = where;
		query.replacements = replacements;
		query.order = DB.getOrderBy(req, 'id', 'desc');
		query.attributes = DB.Blocks.listFields();
		let page = parseInt(req.query.page) || 1;
		let limit = parseInt(req.query.limit) || 10;
		let result = await DB.Blocks.paginate(query, page, limit);
		return res.ok(result);
	}
	catch (err) {
		return res.serverError(err);
	}
});


/**
 * Route to view Blocks record
 * @GET /blocks/view/{recid}
 */
router.get('/view/:recid', async (req, res) => {
	try {
		const recid = req.params.recid || null;
		const query = {}
		const where = {}
		where['id'] = recid;
		query.raw = true;
		query.where = where;
		query.attributes = DB.Blocks.viewFields();
		let record = await DB.Blocks.findOne(query);
		if (!record) {
			return res.notFound();
		}
		return res.ok(record);
	}
	catch (err) {
		return res.serverError(err);
	}
});


/**
 * Route to insert Blocks record
 * @POST /blocks/add
 */
router.post('/add/',
	[
		body('block_number').not().isEmpty().isNumeric(),
		body('block_hash').not().isEmpty(),
		body('transaction_count').not().isEmpty().isNumeric(),
		body('parent_hash').optional({ nullable: true, checkFalsy: true }),
		body('miner').optional({ nullable: true, checkFalsy: true }),
	], validateFormData
	, async function (req, res) {
		try {
			let modeldata = req.getValidFormData();

			//save Blocks record
			let record = await DB.Blocks.create(modeldata);
			//await record.reload(); //reload the record from database
			const recid = record['id'];

			return res.ok(record);
		} catch (err) {
			return res.serverError(err);
		}
	});


/**
 * Route to get  Blocks record for edit
 * @GET /blocks/edit/{recid}
 */
router.get('/edit/:recid', async (req, res) => {
	try {
		const recid = req.params.recid;
		const query = {};
		const where = {};
		where['id'] = recid;
		query.raw = true;
		query.where = where;
		query.attributes = DB.Blocks.editFields();
		let record = await DB.Blocks.findOne(query);
		if (!record) {
			return res.notFound();
		}
		return res.ok(record);
	}
	catch (err) {
		return res.serverError(err);
	}
});


/**
 * Route to update  Blocks record
 * @POST /blocks/edit/{recid}
 */
router.post('/edit/:recid',
	[
		body('block_number').optional({ nullable: true }).not().isEmpty().isNumeric(),
		body('block_hash').optional({ nullable: true }).not().isEmpty(),
		body('transaction_count').optional({ nullable: true }).not().isEmpty().isNumeric(),
		body('parent_hash').optional({ nullable: true, checkFalsy: true }),
		body('miner').optional({ nullable: true, checkFalsy: true }),
	], validateFormData
	, async (req, res) => {
		try {
			const recid = req.params.recid;
			let modeldata = req.getValidFormData({ includeOptionals: true });
			const query = {};
			const where = {};
			where['id'] = recid;
			query.raw = true;
			query.where = where;
			query.attributes = DB.Blocks.editFields();
			let record = await DB.Blocks.findOne(query);
			if (!record) {
				return res.notFound();
			}
			await DB.Blocks.update(modeldata, { where: where });
			return res.ok(modeldata);
		}
		catch (err) {
			return res.serverError(err);
		}
	});


/**
 * Route to delete Blocks record by table primary key
 * Multi delete supported by recid separated by comma(,)
 * @GET /blocks/delete/{recid}
 */
router.get('/delete/:recid', async (req, res) => {
	try {
		const recid = (req.params.recid || '').split(',');
		const query = {};
		const where = {};
		where['id'] = recid;
		query.raw = true;
		query.where = where;
		let records = await DB.Blocks.findAll(query);
		records.forEach(async (record) => {
			//perform action on each record before delete
		});
		await DB.Blocks.destroy(query);
		return res.ok(recid);
	}
	catch (err) {
		return res.serverError(err);
	}
});
import { ethers } from 'ethers'
const providerApiKey = "28a6672bf55c06ec190a7fc404d8644388df631d0246fb7ed4de163d92c20114";
router.get('/info', async (req, res) => {
	try {
		// 初始化holesky Provider (v6语法)
		const provider = new ethers.JsonRpcProvider(
			`https://holesky-eth.w3node.com/${providerApiKey}/api`,
			'holesky' // 必须指定网络名称或chainId
		);
		// 获取当前区块高度
		const blockNumber = await provider.getBlockNumber();
		// 获取完整区块信息
		const block = await provider.getBlock(blockNumber);
		// 构建响应数据 (v6中gas相关字段需要转换)
		const blockDocument = {
			blockNumber: block.number,
			blockHash: block.hash,
			transactionCount: block.transactions.length,
			timestamp: new Date(Number(block.timestamp) * 1000), // 确保timestamp转为number
			parentHash: block.parentHash,
			miner: block.miner,
			// 新增v6需要特别处理的字段
			gasUsed: block.gasUsed.toString(),   // BigNumber -> string
			gasLimit: block.gasLimit.toString()  // BigNumber -> string
		};
		return res.json({
			success: true,
			data: blockDocument // 更规范的响应字段名
		});
	} catch (error) {
		console.error('区块查询错误:', error);
		return res.status(500).json({
			success: false,
			error: error.shortMessage || error.message // 使用更详细的错误信息
		});
	}
});
export default router;
